import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/posts'
    },
    {
      path: '/posts',
      name: 'posts',
      component: () => import('@/views/Posts.vue'),
      meta: { title: '文章列表' }
    },
    {
      path: '/posts/:id',
      name: 'post-detail',
      component: () => import('@/views/PostDetail.vue'),
      meta: { title: '文章详情' }
    },
    {
      path: '/write',
      name: 'write',
      component: () => import('@/views/Write.vue'),
      meta: { title: '写文章', requiresAuth: true }
    },
    {
      path: '/edit/:id',
      name: 'edit',
      component: () => import('@/views/Edit.vue'),
      meta: { title: '编辑文章', requiresAuth: true }
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/Login.vue'),
      meta: { title: '登录' }
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/views/Register.vue'),
      meta: { title: '注册' }
    },
    {
      path: '/profile',
      name: 'profile',
      component: () => import('@/views/Profile.vue'),
      meta: { title: '个人中心', requiresAuth: true }
    },
    {
      path: '/drafts',
      name: 'drafts',
      component: () => import('@/views/Drafts.vue'),
      meta: { title: '草稿箱', requiresAuth: true }
    },
    {
      path: '/my-posts',
      name: 'my-posts',
      component: () => import('@/views/MyPosts.vue'),
      meta: { title: '我的博客', requiresAuth: true }
    },
    {
      path: '/test',
      name: 'test',
      component: () => import('@/views/Test.vue'),
      meta: { title: '测试页面' }
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'not-found',
      component: () => import('@/views/NotFound.vue'),
      meta: { title: '页面不存在' }
    }
  ]
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 现代化博客系统`
  }
  
  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    // 如果有token但用户信息为空，先获取用户信息
    if (userStore.token && !userStore.user) {
      try {
        await userStore.fetchUserInfo()
      } catch (error) {
        // 如果获取用户信息失败，清除token并重定向到登录页
        userStore.logout()
        next({ name: 'login' })
        return
      }
    }
    
    // 检查是否已登录
    if (!userStore.isLoggedIn) {
      next({ name: 'login' })
      return
    }
  }
  
  next()
})

export default router
